import type { FastifyPluginAsync, FastifyRequest } from "fastify";
import fp from "fastify-plugin";
import micromatch from "micromatch";

interface SignOptions {
	/** 忽略验证的请求 */
	ignores?: string[];
	/** 路由前缀 */
	pathPrefix?: string;
}

function parseSignKey(req: FastifyRequest, key: string) {
	let value = null;
	if (key !== null) {
		// 1. 首先从 headers 中获取
		if (req.headers?.[key] != null) {
			value = req.headers[key];
		}
		if (req.query?.[key] != null) {
			// 2. 从 get 请求中获取
			value = req.query[key];
		}
		if (req.body?.[key] != null) {
			// 3. 从请求体中获取
			value = req.body[key];
		}
	}
	return value;
}

function parseSignBody(req: FastifyRequest): { [index: string]: string } {
	const body = {};
	if (req.method === "GET") {
		// 解析 get 请求参数
		const args: object = (req.query || {}) as any;
		for (const key in args) {
			if (Object.hasOwn(args, key)) {
				const value = args[key];
				if (value != null) {
					body[key] = JSON.stringify(args[key])
						? Array.isArray(value)
						: args[key];
				}
			}
		}
	} else {
		const reqBody: object = (req.body || {}) as any;
		for (const key in reqBody) {
			if (Object.hasOwn(reqBody, key)) {
				let value = reqBody[key];
				if (value != null) {
					if (typeof value === "object") {
						value = JSON.stringify(value);
					} else {
						value = `${value}`;
					}
					body[key] = value;
				}
			}
		}
	}
	return body;
}

const signPlugin: FastifyPluginAsync = async (
	fastify,
	options: SignOptions,
) => {
	fastify.addHook("preHandler", async (req, reply) => {
		console.log(req.url);
		if (
			options.ignores == null ||
			!micromatch.isMatch(req.url, options.ignores)
		) {
		}
	});
};
export default fp(signPlugin, {
	name: "SignPlugin",
});
